<!--
前端发送xml数据给后端，后端通过thymeleaf渲染xml模版后返回xml报文给前端，前端解析xml后在前端进行显示
-->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>发送 XML 数据到后端</title>
    <meta charset="UTF-8">
</head>
<body>
<h1>发送 XML 数据到后端</h1>
<form id="xmlForm">
    <label>姓名：</label>
    <input type="text" name="name" id="name" required><br>
    <label>年龄：</label>
    <input type="number" name="age" id="age" required><br>
    <!--<button type="submit">提交</button>-->
    <button type="submit" id="submitButton">提交</button>
</form>
</form>

<script>
    document.getElementById('xmlForm').addEventListener('submit', function (event) {
        event.preventDefault(); // 阻止默认的表单提交

        // 获取表单数据
        const name = document.getElementById('name').value;
        const age = document.getElementById('age').value;

        // 构造 XML 数据
        const xmlData = `
                <person>
                    <name>${name}</name>
                    <age>${age}</age>
                </person>
            `;

        // 使用 fetch API 发送请求
        fetch('/processXml2', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/xml', // 声明数据格式为 XML
            },
            body: xmlData,
        }).then(response =>{
            if(!response.ok){
                throw new Error('网络响应失败，状态码: ' + response.status);
            }
            return response.text(); //读取返回的xml文本
        }).then(xmlString =>{
            const parser = new DOMParser();
            const xmlDoc = parser.parseFromString(xmlString,"application/xml");

            //从xml中获取name和age的值
            const name = xmlDoc.getElementsByTagName("name")[0].textContent;
            const age = xmlDoc.getElementsByTagName("age")[0].textContent;
            alert(name+age);

            // 将解析的值显示到页面中
            document.getElementById('name').value = name;
            document.getElementById('age').value = age;

            //将解析的值显示到页面中并设置为只读
            document.getElementById('name').setAttribute("readonly",true);
            document.getElementById('age').setAttribute("readonly",true);

            //设置提交按钮为禁用
            document.getElementById('submitButton').setAttribute("disabled",true);



        }).catch(error => {
            console.error('解析或网络请求失败:', error);
            alert('无法加载数据，请检查后端服务或网络连接。');
        });
    });
</script>
</body>
</html>